package ua.cs.stu.ics.GUI;

import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.attribute.standard.JobName;
import javax.print.attribute.standard.MediaPrintableArea;
import javax.print.attribute.standard.OrientationRequested;
import javax.swing.*;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.Graphics;
import java.awt.Graphics2D;

import java.awt.Rectangle;
import java.awt.Font;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.ComponentOrientation;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import ua.cs.stu.ics.dao.dbf.StudentDAO;
import ua.cs.stu.ics.dbf.DBReaderFactory;
import ua.cs.stu.ics.label.JLabelExtended;
import ua.cs.stu.ics.print.Printer;
import ua.cs.stu.ics.xml.Dom4jReader;
import ua.cs.stu.ics.xml.Dom4jWriter;

import java.awt.Point;
import java.util.List;
import javax.swing.JToolBar;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import java.awt.Cursor;
import javax.swing.JPanel;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.ImageIcon;
import java.awt.event.KeyEvent;

public class MainGUI {

    private JComboBox jComboBox = null;

    /**
     * Здесь выводится бланки на экран
     */
    private ImagePanel jPanel2 = null;
    private ImagePanel jPanel1 = null;

    /**
     * Здесь выводится бланки для печати
     */
    private ImagePanel jPanel2Print = null;
    private ImagePanel jPanel1Print = null;

    /**
     * currentPanel
     * Панелька которая отображается на екране в данный момент времени
     */
    private ImagePanel currentPanel = null;

    private JFrame jFrame = null; // @jve:decl-index=0:visual-constraint="59,-17"
    private JPanel jContentPane = null;
    private JButton jButton1 = null;
    private JButton jButtonSave = null;
    private JButton jButtonLoad = null;
    private DBReaderFactory dBReaderFactory; // @jve:decl-index=0:
    private Dom4jReader dom4jReader;
    private Dom4jWriter dom4jWriter;

    private FirstBlankView firstBlankView;
    private FirstBlankView firstBlankViewPrint;

    private SecondBlankView secondBlankView;
    private SecondBlankView secondBlankViewPrint;

    private ApplicationContext applicationContext;

    public MainGUI() {
        applicationContext = new ClassPathXmlApplicationContext("context.xml");
        setdBReaderFactory((DBReaderFactory) applicationContext
                .getBean("dBReaderFactory"));
        setStudentDAO((StudentDAO) applicationContext.getBean("studentDAO"));

        getJFrame().setVisible(true);
    }

    public Dom4jReader getDom4jReader() {
        if (dom4jReader == null)
            dom4jReader = new Dom4jReader();
        return dom4jReader;
    }

    public Dom4jWriter getDom4jWriter() {
        if (dom4jWriter == null)
            dom4jWriter = new Dom4jWriter();
        return dom4jWriter;
    }

    public DBReaderFactory getdBReaderFactory() {
        return dBReaderFactory;
    }

    public void setdBReaderFactory(DBReaderFactory dBReaderFactory) {
        this.dBReaderFactory = dBReaderFactory;
    }

    public StudentDAO getStudentDAO() {
        return studentDAO;
    }

    public void setStudentDAO(StudentDAO studentDAO) {
        this.studentDAO = studentDAO;
    }

    private StudentDAO studentDAO;

    private JToolBar jToolBar = null;
    private JButton jButton2 = null;

    /**
     * This method initializes jFrame
     *
     * @return javax.swing.JFrame
     */
    private JFrame getJFrame() {
        if (jFrame == null) {
            jFrame = new JFrame();
            jFrame.setBounds(new Rectangle(0, 0, 856, 655));
            jFrame.setEnabled(true);
            jFrame.setResizable(true);
            jFrame.setBackground(Color.white);
            jFrame.setVisible(true);
            getJButton1().setEnabled(false);
            jFrame.setContentPane(getJContentPane());
            jFrame.setResizable(false);
            jFrame.setTitle("Распечатка вкладышей");
            jFrame.addWindowListener(new WindowListener() {
                public void windowOpened(WindowEvent e) {
                }

                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }

                public void windowClosed(WindowEvent e) {
                }

                public void windowIconified(WindowEvent e) {
                }

                public void windowDeiconified(WindowEvent e) {
                }

                public void windowActivated(WindowEvent e) {
                }

                public void windowDeactivated(WindowEvent e) {
                }
            });
        }
        return jFrame;
    }

    /**
     * This method initializes jContentPane
     *
     * @return javax.swing.JPanel
     */
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BoxLayout(getJContentPane(),
                    BoxLayout.Y_AXIS));
            jContentPane.setBackground(Color.WHITE);
            jContentPane.add(getJToolBar(), null);
            jContentPane.add(getJPanel1(), null);
            currentPanel = getJPanel1Print();
//            jContentPane.get
        }
        return jContentPane;
    }

    /**
     * This method initializes jButton1
     *
     * @return javax.swing.JButton
     */
    private JButton getJButton1() {
        if (jButton1 == null) {
            jButton1 = new JButton();
            jButton1.setName("jButton1");
            jButton1.setHorizontalTextPosition(SwingConstants.LEFT);
            jButton1.setHorizontalAlignment(SwingConstants.LEFT);
            jButton1.setToolTipText("печатать бланк");
            jButton1.setVisible(true);
            jButton1.setIcon(new ImageIcon(("resource/icons/print_printer.png")));

            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    currentPanel.setBackground(Color.WHITE);
                    currentPanel.setForeground(Color.WHITE);
                    ImagePanel iPanel = currentPanel.equals(getJPanel1Print()) ? getJPanel1() : getJPanel2();
                    getDom4jWriter().save("config/__tmp.xml", iPanel, true);
                    getDom4jReader().load("config/__tmp.xml", currentPanel);
                    Printer.printComponenet(currentPanel);
                }
            });
        }
        return jButton1;
    }

    private JButton getJButtonSave() {
        if (jButtonSave == null) {
            jButtonSave = new JButton();
            jButtonSave.setName("jButtonSave");
            jButtonSave.setHorizontalTextPosition(SwingConstants.LEFT);
            jButtonSave.setText("");
            jButtonSave.setHorizontalAlignment(SwingConstants.LEFT);

            jButtonSave.setSize(new Dimension(35, 35));
            jButtonSave.setPreferredSize(new Dimension(35, 35));
            jButtonSave.setToolTipText("сохранить настройки");
            jButtonSave.setVisible(true);
            jButtonSave.setIcon(new ImageIcon(("resource/icons/save.png")));
            jButtonSave.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    FileDialog fd = new FileDialog(getJFrame(), "Сохранить настройки", FileDialog.SAVE);
                    fd.setFile("config.xml");
                    fd.setDirectory("config");
                    fd.setLocation(50, 50);
                    fd.show();
                    if (fd.getFile() != null) {
                        ImagePanel iPanel = currentPanel.equals(getJPanel1Print()) ? getJPanel1() : getJPanel2();
                        getDom4jWriter().save(fd.getDirectory() + fd.getFile(), iPanel, false);
                    }
                }
            });
        }
        return jButtonSave;
    }

    private JButton getjButtonLoad() {
        if (jButtonLoad == null) {
            jButtonLoad = new JButton();
            jButtonLoad.setName("jButtonLoad");
            jButtonLoad.setHorizontalTextPosition(SwingConstants.LEFT);
            jButtonLoad.setText("");
            jButtonLoad.setHorizontalAlignment(SwingConstants.LEFT);
            jButtonLoad.setIcon(new ImageIcon(("resource/icons/download.png")));
            jButtonLoad.setToolTipText("загрузить настройки");
            jButtonLoad.setVisible(true);
            jButtonLoad.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    FileDialog fd = new FileDialog(getJFrame(), "Загрузить настройки", FileDialog.LOAD);
                    fd.setFile("*.xml");
                    fd.setDirectory("config");
                    fd.setLocation(50, 50);
                    fd.show();
                    if (fd.getFile() != null) {
                        ImagePanel iPanel = currentPanel.equals(getJPanel1Print()) ? getJPanel1() : getJPanel2();
                        getDom4jReader().load(fd.getDirectory() + fd.getFile(), iPanel);
                    }
                }
            });
        }
        return jButtonLoad;
    }

    /**
     * This method initializes jPanel1
     *
     * @return javax.swing.JPanel
     */
    private ImagePanel getJPanel1() {
        if (jPanel1 == null) {
            jPanel1 = getFirstBlankView().create("resource/1.jpg");
        }
        return jPanel1;
    }

    private ImagePanel getJPanel1Print() {
        if (jPanel1Print == null) {
            jPanel1Print = getFirstBlankViewPrint().create("");

        }
        return jPanel1Print;
    }

    /**
     * This method initializes jComboBox
     *
     * @return javax.swing.JComboBox
     */

    /**
     * This method initializes jComboBox
     *
     * @return javax.swing.JComboBox
     */
    private JComboBox getJComboBox2() {
        if (jComboBox == null) {
            dBReaderFactory.init();
            List<String> fio = studentDAO.findFIOs();

            jComboBox = new JComboBox(fio.toArray());
            jComboBox.setEditable(true);
            jComboBox.setPreferredSize(new Dimension(400, 70));
            jComboBox.setName("jComboBox");
            jComboBox.setSelectedIndex(-1);

            jComboBox.setEnabled(true);
            jComboBox.setMaximumSize(new Dimension(220, 28));
            jComboBox.setMinimumSize(new Dimension(220, 28));
            jComboBox.setVisible(true);
            jComboBox.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    jButton1.setVisible(true);
                    jButtonSave.setVisible(true);
                    jButtonLoad.setVisible(true);
                    String name = jComboBox.getSelectedItem().toString();
                    getFirstBlankView().edit(name);
                    getFirstBlankViewPrint().edit(name);

                    getSecondBlankView().view(studentDAO.findStudent(name));
                    getSecondBlankViewPrint()
                            .view(studentDAO.findStudent(name));
                    getJButton1().setEnabled(true);

                    if (currentPanel.equals(getJPanel1Print()))
                        getJPanel1().repaint();
                    else
                        getJPanel2().repaint();
                }
            });

            new AutoCompleteCombo(jComboBox);

        }
        return jComboBox;
    }

    /**
     * This method initializes jPanel2
     *
     * @return javax.swing.JPanel
     */
    private ImagePanel getJPanel2() {
        if (jPanel2 == null) {
            jPanel2 = new ImagePanel("resource/2.jpg");
            jPanel2.setLayout(null);
        }
        return jPanel2;
    }

    private ImagePanel getJPanel2Print() {
        if (jPanel2Print == null) {
            jPanel2Print = new ImagePanel("");
            jPanel2Print.setLayout(null);
            jPanel2Print.setLocation(new Point(5, 5));
            jPanel2Print.setSize(new Dimension(842, 595));

        }
        return jPanel2Print;
    }

    public SecondBlankView getSecondBlankView() {
        if (secondBlankView == null) {
            secondBlankView = (SecondBlankView) applicationContext
                    .getBean("secondBlankView");
            secondBlankView.setjPanel(getJPanel2());
        }
        return secondBlankView;
    }

    public SecondBlankView getSecondBlankViewPrint() {
        if (secondBlankViewPrint == null) {
            secondBlankViewPrint = (SecondBlankView) applicationContext
                    .getBean("secondBlankViewPrint");
            secondBlankViewPrint.setjPanel(getJPanel2Print());
        }
        return secondBlankViewPrint;
    }

    public FirstBlankView getFirstBlankView() {
        if (firstBlankView == null) {
            firstBlankView = (FirstBlankView) applicationContext
                    .getBean("firstBlankView");
            firstBlankView.setjPanel(getJPanel1());

        }
        return firstBlankView;
    }

    public FirstBlankView getFirstBlankViewPrint() {
        if (firstBlankViewPrint == null) {
            firstBlankViewPrint = (FirstBlankView) applicationContext
                    .getBean("firstBlankViewPrint");
            firstBlankViewPrint.setjPanel(getJPanel1Print());

        }
        return firstBlankViewPrint;
    }

    /**
     * This method initializes jToolBar
     *
     * @return javax.swing.JToolBar
     */
    private JToolBar getJToolBar() {
        if (jToolBar == null) {
            jToolBar = new JToolBar();
            jToolBar.setFloatable(false);
            jToolBar.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
            jToolBar.setBorder(null);
            jToolBar.setPreferredSize(new Dimension(470, 34));
            jToolBar.add(getJButton2());
            jToolBar.add(getJButton1());
            jToolBar.add(getJButtonSave());
            jToolBar.add(getjButtonLoad());
            jToolBar.add(getJComboBox2());
        }
        return jToolBar;
    }

    /**
     * This method initializes jButton2
     *
     * @return javax.swing.JButton
     */
    private JButton getJButton2() {
        if (jButton2 == null) {
            jButton2 = new JButton();
            jButton2.setIcon(new ImageIcon(("resource/icons/refresh.png")));
            jButton2.setToolTipText("повернуть бланк");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    if (currentPanel.equals(getJPanel1Print())) {
                        getJContentPane().remove(getJPanel1());
                        getJContentPane().add(getJPanel2(), null);
                        getJPanel2().setVisible(true);
                        getJPanel2().setSize(getJPanel1().getWidth(), getJPanel1().getWidth());
                        getJPanel2().setLocation(getJPanel1().getX(), getJPanel1().getY());
                        currentPanel = getJPanel2Print();
                        getJPanel2().repaint();
                    } else {
                        getJContentPane().remove(getJPanel2());
                        getJContentPane().add(getJPanel1(), null);
                        getJPanel1().setVisible(true);
                        getJPanel1().setSize(getJPanel2().getWidth(), getJPanel2().getWidth());
                        getJPanel1().setLocation(getJPanel2().getX(), getJPanel2().getY());
                        currentPanel = getJPanel1Print();
                        getJPanel1().repaint();
                    }
                }
            });
        }
        return jButton2;
    }

    public static void main(String[] args) {
        MainGUI application = new MainGUI();

    }
}
